package com.serene.authority.admin.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serene.authority.admin.annotation.DataPermission;
import com.serene.authority.admin.entity.MyRoleUser;
import com.serene.authority.admin.entity.MyUser;
import com.serene.authority.admin.entity.MyUserJob;
import com.serene.authority.admin.mapper.RoleUserMapper;
import com.serene.authority.admin.mapper.UserMapper;
import com.serene.authority.admin.mapper.UserJobMapper;
import com.serene.authority.admin.service.RoleUserService;
import com.serene.authority.admin.service.UserJobService;
import com.serene.authority.admin.service.UserService;
import com.serene.authority.common.exceptionhandler.MyException;
import com.serene.authority.common.utils.Result;
import com.serene.authority.common.utils.ResultCode;
import com.serene.authority.common.utils.UserConstants;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

/**
 * @author serene
 * @createTime 2020/7/10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, MyUser> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleUserMapper roleUserMapper;

    @Autowired
    private UserJobMapper userJobMapper;

    @Autowired
    private RoleUserService roleUserService;

    @Autowired
    private UserJobService userJobService;


    @Override
    @DataPermission(deptAlias = "d", userAlias = "u")
    public Result<MyUser> getAllUsersByPage(Integer offectPosition, Integer limit, MyUser myUser) {
        Page page = PageHelper.offsetPage(offectPosition, limit);
        List<MyUser> fuzzyUserByPage = userMapper.getFuzzyUserByPage(myUser);
        return Result.ok().count(page.getTotal()).data(fuzzyUserByPage).code(ResultCode.TABLE_SUCCESS);
    }


    /**
     * 根据id返回用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public MyUser getUserById(Integer userId) {
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public void checkUserAllowed(MyUser user) {
        if (!StringUtils.isEmpty(user.getUserId()) && user.isAdmin()) {
            throw new MyException(ResultCode.ERROR, "不允许操作超级管理员用户");
        }
    }

    @Override
    public String checkPhoneUnique(MyUser myUser) {
        Integer userId = ObjectUtil.isEmpty(myUser.getUserId()) ? -1 : myUser.getUserId();
        MyUser info = checkPhoneUnique(myUser.getPhone());
        if (ObjectUtil.isNotEmpty(info) && !info.getUserId().equals(userId)) {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }


    @Override
    public String checkUserNameUnique(MyUser myUser) {
        Integer userId = ObjectUtil.isEmpty(myUser.getUserId()) ? -1 : myUser.getUserId();
        MyUser info = checkUsernameUnique(myUser.getUserName());
        if (ObjectUtil.isNotEmpty(info) && !info.getUserId().equals(userId)) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    @Override
    public Result<MyUser> updateUser(MyUser myUser, Integer roleId) {
        if (roleId != null) {
            userMapper.updateUser(myUser);
            MyRoleUser myRoleUser = new MyRoleUser();
            myRoleUser.setUserId(myUser.getUserId());
            myRoleUser.setRoleId(roleId);
            if (roleUserService.queryRoleByUserByUserId(myUser.getUserId()) != null) {
                roleUserMapper.updateMyRoleUser(myRoleUser);
            } else {
                roleUserMapper.insert(myRoleUser);
            }
            userJobService.deleteUserJobCountByUserId(myUser.getUserId());
            insertUserPost(myUser);
            return Result.ok().message("更新成功");
        } else {
            return Result.error().message("更新失败");
        }
    }

    @Override
    public int changeStatus(MyUser user) {
        return userMapper.updateUser(user);
    }


    /**
     * 添加用户信息
     *
     * @param user 用户信息类
     * @return
     */
    @Override
    public Integer saveUser(MyUser user) {
        user.setCreateTime(now());
        user.setUpdateTime(now());
        return userMapper.insert(user);
    }

    /**
     * 新建用户
     *
     * @param myUser
     * @param roleId
     * @return
     */
    @Override
    public Result<MyUser> save(MyUser myUser, Integer roleId) {
        if (roleId != null) {
            //新增用户信息
            saveUser(myUser);

            MyRoleUser myRoleUser = new MyRoleUser();
            myRoleUser.setRoleId(roleId);
            myRoleUser.setUserId(myUser.getUserId().intValue());
            //给用户分配角色
            roleUserMapper.insert(myRoleUser);

            //新增用户岗位信息
            insertUserPost(myUser);
            return Result.ok().message("添加成功，初始密码123456");
        }

        return Result.error().message("添加失败");
    }


    /**
     * 通过id删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public int deleteUser(Integer userId) {
        checkUserAllowed(new MyUser(userId));
        //删除用户角色
        roleUserService.deleteRoleUserByUserId(userId);
        //删除用户岗位
        userJobService.deleteUserJobCountByUserId(userId);
        //通过id删除用户
        return deleteUserById(userId);
    }

    /**
     * 通过id删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public Integer deleteUserById(Integer userId) {
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userMapper.delete(wrapper);
    }

    @Override
    public MyUser getUserByName(String userName) {
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        return userMapper.selectOne(wrapper);
    }

    /**
     * 通过手机返回用户
     *
     * @param phone
     * @return
     */
    @Override
    public MyUser checkPhoneUnique(String phone) {
        QueryWrapper<MyUser> wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        wrapper.last("limit 1");
        return userMapper.selectOne(wrapper);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName
     * @return
     */
    @Override
    public MyUser checkUsernameUnique(String userName) {
        QueryWrapper<MyUser> wrapper = new QueryWrapper();
        wrapper.eq("user_name", userName);
        wrapper.last("limit 1");
        return userMapper.selectOne(wrapper);
    }


    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(MyUser user) {
        Integer[] jobs = user.getJobIds();

        if (ArrayUtil.isNotEmpty(jobs)) {
            // 新增用户与岗位管理
            List<MyUserJob> list = new ArrayList<MyUserJob>();
            for (Integer jobId : jobs) {
                MyUserJob up = new MyUserJob();
                up.setUserId(user.getUserId());
                up.setJobId(jobId);
                list.add(up);
            }
            if (list.size() > 0) {
                userJobMapper.batchUserJob(list);
            }
        }
        return;
    }
}
